from datetime import date, datetime, timedelta
from google.appengine.api.urlfetch import fetch
from horseanalysis.model.race import Race
import re

class RaceDayFetcher:
  def __init__(self):
    pass
  
  def get_race_data(self, date, race_no, venue):
    if venue == 'ST':
      venue_full_name =  'Sha Tin'
    elif venue == 'HV':
      venue_full_name = 'Happy Valley'
      
    date_query = date.strftime("%d-%m-%Y")
    date_match = date.strftime("%d/%m/%Y")
    
    data = fetch('http://bet.hkjc.com/racing/pages/odds_wp.aspx?date=%(date)s&venue=%(venue)s&raceno=%(race_no)d&lang=en' % \
      {'date':date_query, 'race_no':race_no, 'venue': venue})
    content = data.content
      
    for result in re.finditer(r", <nobr>([0-9/]*)</nobr>, <nobr>([0-9]*):([0-9]*)</nobr>, ", content):
      content_date = result.group(1)
      content_hour = result.group(2)
      content_min = result.group(3)
      
      race_no_search = re.search("<strong>Race %(race_no)d</strong>" % {'race_no': race_no}, content)
      venue_search = re.search("<nobr>%(venue_full_name)s</nobr>" % {'venue_full_name': venue_full_name}, content)
      
      if content_date == date_match and race_no_search and venue_search:
        race_time = datetime(date.year, date.month, date.day, int(content_hour) - 8, int(content_min), 0)
        if Race.create_if_not_existed(race_no, race_time, venue):
          return True
    
    return False
  
  def create_race_if_need(self):
    tomorrow = datetime.now() + timedelta(days=1)
    
    for venue in ['HV', 'ST']:
      for race_no in range(1, 13):
        if not self.get_race_data(tomorrow, race_no, venue):
          break
        
    return True